package com.hznu.management.aop;

import com.alibaba.fastjson.JSON;
import com.hznu.management.annotation.SystemLog;
import com.hznu.management.entity.Log;
import com.hznu.management.service.LogService;
import com.hznu.management.thread.SaveSystemLogThread;
import com.hznu.management.utils.IpInfoUtil;
import com.hznu.management.utils.ThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Aspect
@Component
public class LogAspect {

    private static final ThreadLocal<Date> beginTimeThreadLocal = new NamedThreadLocal<Date>("ThreadLocal beginTime");

    @Autowired
    private LogService logService;

    @Autowired(required = false)
    private HttpServletRequest request;

    @Autowired
    private IpInfoUtil ipInfoUtil;

    private final Log systemLog = new Log();


    @Pointcut("@annotation(com.hznu.management.annotation.SystemLog)")
    public void controllerAspect() {
    }

    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) throws Exception {
        //线程绑定变量（该数据只有当前请求的线程可见）
        Date beginTime = new Date();
        beginTimeThreadLocal.set(beginTime);
        //获取注解中的description属性值
        String description = getControllerMethodInfo(joinPoint).get("description").toString();
        //日志标题
        systemLog.setName(description);
        //日志类型
        systemLog.setLogType((int) getControllerMethodInfo(joinPoint).get("type"));
        //日志请求url
        systemLog.setRequestUrl(request.getRequestURI());
        //请求方式
        systemLog.setRequestType(request.getMethod());

        //获取body体中参数
        HashMap<String, Object> params = new HashMap<>();
        Object[] args = joinPoint.getArgs();
        params.put("body", args);

        //获取url中的请求参数
        Map<String, String[]> requestParams = request.getParameterMap();
        params.put("head", requestParams);

        //设置请求参数
        systemLog.setRequestParam(JSON.toJSONString(params));
        //其他属性
        systemLog.setIp(ipInfoUtil.getIpAddr(request));
        systemLog.setCreateBy("system");
        systemLog.setDelFlag(0);
        systemLog.setStartTime(beginTime);
    }


    @Around("controllerAspect()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object proceed = null;
        try {
            proceed = proceedingJoinPoint.proceed();
            systemLog.setStatus(0);
        } catch (Exception e) {
            log.error("AOP环绕通知通知异常", e);
            systemLog.setStatus(1);
        }
        return proceed;
    }


    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
    public static Map<String, Object> getControllerMethodInfo(JoinPoint joinPoint) throws Exception {

        Map<String, Object> map = new HashMap<String, Object>(16);
        //获取目标类名
        String targetName = joinPoint.getTarget().getClass().getName();
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        //获取相关参数
        Object[] arguments = joinPoint.getArgs();
        //生成类对象
        Class targetClass = Class.forName(targetName);
        //获取该类中的方法
        Method[] methods = targetClass.getMethods();
        String description = "";
        Integer type = null;
        for (Method method : methods) {
            if (!method.getName().equals(methodName)) {
                continue;
            }
            Class[] clazzs = method.getParameterTypes();
            if (clazzs.length != arguments.length) {
                //比较方法中参数个数与从切点中获取的参数个数是否相同，原因是方法可以重载哦
                continue;
            }
            description = method.getAnnotation(SystemLog.class).description();
            type = method.getAnnotation(SystemLog.class).type().getVal();
            map.put("description", description);
            map.put("type", type);
        }
        return map;
    }


    @After("controllerAspect()")
    public void doAfter(JoinPoint joinPoint) {
        //请求开始时间
        long beginTime = beginTimeThreadLocal.get().getTime();
        //请求结束时间
        long endTime = System.currentTimeMillis();
        systemLog.setEndTime(new Date(endTime));
        //请求耗时
        Long logElapsedTime = endTime - beginTime;
        systemLog.setCostTime(logElapsedTime.intValue());
        //日志记录创建时间
        systemLog.setCreateTime(new Date());
        ThreadPoolUtil.getPool().execute(new SaveSystemLogThread(systemLog, logService));
    }
}
